<template>
  <div class="recruitment-plan">
    <div class="page-header">
      <h2>招生计划管理</h2>
      <div class="page-info">
        <el-tag size="small" type="info">数据统计</el-tag>
        <span class="stat-item"><i class="el-icon-data-line"></i> 计划总数：{{ total }}</span>
      </div>
    </div>
    
    <el-card class="box-card" shadow="hover">
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增计划</el-button>
        <el-form :inline="true" :model="queryParams" class="search-form" @submit.native.prevent>
          <el-form-item>
            <el-select v-model="queryParams.year" placeholder="选择年份" clearable size="small">
              <el-option
                v-for="item in yearOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.province" placeholder="选择省份" clearable size="small">
              <el-option
                v-for="item in provinceOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.batch" placeholder="选择批次" clearable size="small">
              <el-option
                v-for="item in batchOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.subject" placeholder="选择科类" clearable size="small">
              <el-option
                v-for="item in subjectTypeOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryParams.major" placeholder="专业名称" clearable size="small"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据统计区域 -->
      <div class="stat-cards">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-s-data"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">计划总数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background-color: #67c23a;">
            <i class="el-icon-date"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ yearOptions.length }}</div>
            <div class="stat-label">年份数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon" style="background-color: #409EFF;">
            <i class="el-icon-location"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ provinceOptions.length }}</div>
            <div class="stat-label">省份数</div>
          </div>
        </div>
      </div>
      
      <div class="action-container">
        <el-button type="danger" :disabled="selectIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
      
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%; margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); border-radius: 4px;"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :stripe="true"
        :highlight-current-row="true">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          prop="year"
          label="年份"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="province"
          label="生源省市"
          width="120">
          <template slot-scope="scope">
            <el-tag size="medium" effect="plain">{{ scope.row.province }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="category"
          label="类别"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.category || '/' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="batch"
          label="批次"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.batch || '/' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="subject"
          label="科类"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.subject || '/' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="major"
          label="招生专业名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="planNumber"
          label="招生计划数"
          width="120"
          align="center">
          <template slot-scope="scope">
            <el-tag type="success" effect="dark">{{ scope.row.planNumber }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              style="color: #F56C6C"
              @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <div v-if="!loading && tableData.length === 0" class="empty-container">
        <el-empty description="暂无招生计划数据">
          <el-button type="primary" size="small" @click="handleAdd">添加招生计划</el-button>
        </el-empty>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size.sync="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      
      <!-- 使用提示 -->
      <div class="tips-container" v-if="tableData.length > 0">
        <div class="tip-icon"><i class="el-icon-info"></i></div>
        <div class="tip-content">
          <div class="tip-title">使用提示</div>
          <div class="tip-text">
            <p>1. 招生计划数据会在小程序端展示给用户</p>
            <p>2. 批量删除功能请谨慎使用</p>
            <p>3. 年份和省份数据是必选项</p>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false" @close="resetForm('form')">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" status-icon>
        <el-form-item label="年份" prop="year">
          <el-select v-model="form.year" placeholder="请选择年份" style="width: 100%">
            <el-option v-for="item in yearOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生源省市" prop="province">
          <el-select v-model="form.province" placeholder="请选择省份" style="width: 100%">
            <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="form.category" placeholder="请输入类别"></el-input>
        </el-form-item>
        <el-form-item label="批次" prop="batch">
          <el-select v-model="form.batch" placeholder="请选择批次" style="width: 100%">
            <el-option v-for="item in batchOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科类" prop="subject">
          <el-select v-model="form.subject" placeholder="请选择科类" style="width: 100%">
            <el-option v-for="item in subjectTypeOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="招生专业名称" prop="major">
          <el-input v-model="form.major" placeholder="请输入招生专业名称"></el-input>
        </el-form-item>
        <el-form-item label="招生计划数" prop="planNumber">
          <el-input-number v-model="form.planNumber" :min="1" :max="1000" style="width: 100%"></el-input-number>
          <div class="form-tip">请输入1-1000之间的数字</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'RecruitmentPlan',
  data() {
    return {
      // 加载状态
      loading: false,
      // 表格数据
      tableData: [],
      // 年份选项
      yearOptions: [],
      // 省份选项
      provinceOptions: [],
      // 批次选项
      batchOptions: [],
      // 科类选项
      subjectTypeOptions: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        year: '',
        province: '',
        batch: '',
        subject: '',
        major: ''
      },
      // 总数据量
      total: 0,
      // 选中的ID列表
      selectIds: [],
      // 弹窗是否可见
      dialogVisible: false,
      // 弹窗标题
      dialogTitle: '',
      // 表单对象
      form: {
        id: undefined,
        year: '',
        province: '',
        category: '',
        batch: '',
        subject: '',
        major: '',
        planNumber: 0
      },
      // 表单验证规则
      rules: {
        year: [
          { required: true, message: '请选择年份', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择生源省市', trigger: 'change' }
        ],
        batch: [
          { required: true, message: '请选择批次', trigger: 'change' }
        ],
        subject: [
          { required: true, message: '请选择科类', trigger: 'change' }
        ],
        major: [
          { required: true, message: '请输入招生专业名称', trigger: 'blur' }
        ],
        planNumber: [
          { required: true, message: '请输入招生计划数', trigger: 'change' },
          { type: 'number', min: 1, message: '计划数必须大于0', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 获取基础信息数据
    this.getYearOptions();
    this.getProvinceOptions();
    this.getBatchOptions();
    this.getSubjectTypeOptions();
    // 获取表格数据
    this.getTableData();
  },
  methods: {
    // 获取年份选项（来自基础信息管理）
    getYearOptions() {
      axios.get('/api/admin/year/list', { params: { page: 1, size: 1000 } }).then(res => {
        if (res.data && res.data.data && res.data.data.records) {
          this.yearOptions = res.data.data.records.map(item => item.year_name || item.yearName);
        } else {
          this.$message.error('获取年份数据失败');
        }
      }).catch(() => {
        this.$message.error('获取年份数据失败');
      });
    },
    // 获取省份选项（来自基础信息管理）
    getProvinceOptions() {
      axios.get('/api/admin/province/list', { params: { page: 1, size: 1000 } }).then(res => {
        if (res.data && res.data.data && res.data.data.records) {
          this.provinceOptions = res.data.data.records.map(item => item.province);
        } else {
          this.$message.error('获取省份数据失败');
        }
      }).catch(() => {
        this.$message.error('获取省份数据失败');
      });
    },
    // 获取批次选项
    getBatchOptions() {
      axios.get('/api/admin/batch/list', { params: { page: 1, size: 1000 } }).then(res => {
        if (res.data && res.data.data && res.data.data.records) {
          this.batchOptions = res.data.data.records.map(item => item.batch_name || item.batchName);
        } else {
          this.$message.error('获取批次数据失败');
        }
      }).catch(() => {
        this.$message.error('获取批次数据失败');
      });
    },
    // 获取科类选项
    getSubjectTypeOptions() {
      axios.get('/api/admin/subject-type/list', { params: { page: 1, size: 1000 } }).then(res => {
        if (res.data && res.data.data && res.data.data.records) {
          this.subjectTypeOptions = res.data.data.records.map(item => item.type_name || item.typeName);
        } else {
          this.$message.error('获取科类数据失败');
        }
      }).catch(() => {
        this.$message.error('获取科类数据失败');
      });
    },
    
    // 获取表格数据
    getTableData() {
      this.loading = true;
      const params = { ...this.queryParams };
      
      console.log('请求参数：', params); // 添加调试日志
      
      axios.get('/api/admin/recruitment-plan/page', {
        params: params
      }).then(res => {
        console.log('API响应：', res.data); // 添加调试日志
        if (res.data && res.data.code === 200) {
          const data = res.data.data;
          this.tableData = data.records || [];
          this.total = data.total || 0;
          console.log('解析后数据：', { records: this.tableData, total: this.total }); // 添加调试日志
        } else {
          this.$message.error('获取招生计划数据失败');
        }
        this.loading = false;
      }).catch((error) => {
        console.error('API请求错误：', error); // 添加错误日志
        this.$message.error('获取招生计划数据失败');
        this.loading = false;
      });
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.page = 1;
      this.getTableData();
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        year: '',
        province: '',
        batch: '',
        subject: '',
        major: ''
      };
      this.getTableData();
    },
    
    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectIds = selection.map(item => item.id);
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getTableData();
    },
    
    // 处理每页数量变化
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.queryParams.page = 1;
      this.getTableData();
    },
    
    // 处理新增
    handleAdd() {
      this.dialogTitle = '新增招生计划';
      this.form = {
        id: undefined,
        year: '',
        province: '',
        category: '',
        batch: '',
        subject: '',
        major: '',
        planNumber: 0
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },
    
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑招生计划';
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },
    
    // 重置表单
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields();
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const isUpdate = this.form.id !== undefined;
          const apiUrl = isUpdate ? '/api/admin/recruitment-plan/update' : '/api/admin/recruitment-plan/add';
          const method = isUpdate ? 'put' : 'post';
          
          axios[method](apiUrl, this.form).then(res => {
            if (res.data && res.data.code === 200) {
              this.$message.success(isUpdate ? '修改成功' : '新增成功');
              this.dialogVisible = false;
              this.getTableData();
            } else {
              this.$message.error(isUpdate ? '修改失败' : '新增失败');
            }
          }).catch(() => {
            this.$message.error(isUpdate ? '修改失败' : '新增失败');
          });
        }
      });
    },
    
    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该招生计划?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/admin/recruitment-plan/delete/${row.id}`).then(res => {
          if (res.data && res.data.code === 200) {
            this.$message.success('删除成功');
            this.getTableData();
          } else {
            this.$message.error('删除失败');
          }
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },
    
    // 处理批量删除
    handleBatchDelete() {
      if (this.selectIds.length === 0) {
        this.$message.warning('请选择要删除的数据');
        return;
      }
      
      this.$confirm(`确认删除已选中的${this.selectIds.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/api/admin/recruitment-plan/batchDelete', {
          data: this.selectIds
        }).then(res => {
          if (res.data && res.data.code === 200) {
            this.$message.success('批量删除成功');
            this.getTableData();
          } else {
            this.$message.error('批量删除失败');
          }
        }).catch(() => {
          this.$message.error('批量删除失败');
        });
      }).catch(() => {});
    }
  }
}
</script>

<style scoped>
.recruitment-plan {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.page-info {
  display: flex;
  align-items: center;
}

.stat-item {
  margin-left: 15px;
  font-size: 13px;
  color: #606266;
}

.box-card {
  flex: 1;
  margin-bottom: 20px;
  box-shadow: 0 4px 18px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.toolbar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar > .el-button {
  margin-right: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

.search-form .el-button {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 统计卡片 */
.stat-cards {
  display: flex;
  gap: 15px;
  margin: 15px 0;
}

.stat-card {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  min-width: 150px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 40px;
  height: 40px;
  background-color: #409EFF;
  color: white;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

.stat-content {
  margin-left: 15px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  margin-top: 5px;
  font-size: 13px;
  color: #909399;
}

.action-container {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.empty-container {
  margin: 40px 0;
  text-align: center;
}

/* 提示区域 */
.tips-container {
  margin-top: 20px;
  padding: 15px;
  display: flex;
  background-color: #f4f6fa;
  border-radius: 4px;
}

.tip-icon {
  font-size: 24px;
  color: #e6a23c;
  margin-right: 15px;
}

.tip-content {
  flex: 1;
}

.tip-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.tip-text {
  color: #606266;
  font-size: 13px;
}

.tip-text p {
  margin: 5px 0;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1;
  padding-top: 4px;
}
</style> 